package com.ucode.application.controller.crm;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.validation.constraints.Size;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ucode.application.form.crm.CustomerForm;
import com.ucode.application.helper.CrmDataPermissionVerifier;
import com.ucode.application.security.CurrentLoginUserService;
import com.ucode.application.vo.crm.FollowupTeamUserVo;
import com.ucode.crm.dictionary.CrmResultDefineMsg;
import com.ucode.crm.dictionary.ModuleType;
import com.ucode.crm.dictionary.TeamUserPower;
import com.ucode.crm.mode.Customer;
import com.ucode.crm.mode.Contacts;
import com.ucode.crm.mode.CrmTeamUser;
import com.ucode.crm.service.CustomerService;
import com.ucode.crm.service.BusinessService;
import com.ucode.crm.service.ContactsService;
import com.ucode.crm.service.CrmTeamUserService;
import com.ucode.crm.vo.BusinessVo;
import com.ucode.crm.vo.CustomerVo;
import com.ucode.search.crm.model.ESCustomer;
import com.ucode.search.crm.service.ESCustomerService;
import com.ucode.springboot.starter.web.validator.group.AddGroup;
import com.ucode.springboot.starter.web.validator.group.UpdateGroup;
import com.ucode.sys.model.User;
import com.ucode.sys.service.UserService;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.ResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import cn.hutool.core.collection.CollUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags="CRM-客户")
@RestController
@RequestMapping("/crm-customer")
@Validated
public class CustomerController {
    
    private static final String moduleCode = "crm";//对应menu->permission
    
    @Autowired
    private CustomerService customerService;
    @Autowired
    private ContactsService contactsService;
    @Autowired
    private BusinessService businessService;
    @Autowired
    private CrmTeamUserService crmTeamUserService;
    @Autowired
    private CurrentLoginUserService currentLoginUserService;
    @Autowired
    private UserService userService;
    @Autowired
    private CrmDataPermissionVerifier dataPermissionVerifier;
    @Autowired
    private ESCustomerService esCustomerService;
    
    @PreAuthorize("hasAuthority('crm:customer:list') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation("非公海客户列表")
    @GetMapping(value = "/list")
    public ResponseResult<Object> list(
            @ApiParam(value ="客户名称/电话/手机号")  @RequestParam(value = "keywords",required = false) String keyword,
            @ApiParam(value ="客户等级")  @RequestParam(value = "level",required = false) Integer level,
            @ApiParam(value ="客户来源")  @RequestParam(value = "source",required = false) Integer source,
            @ApiParam(value ="用户(最多20人)")  @Size(max = 20,message="一次最多选择20人")@RequestParam(value = "userIds",required = false) List<Long> userIds,
            @ApiParam(value ="用户参与角色(0->全部,1->负责的客户2->协作的客户)")  @RequestParam(value = "prole", defaultValue = "0",required = true) Integer prole,
            @ApiParam(value="页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @ApiParam(value="每页记录数",example="20") @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize){
        userIds = dataPermissionVerifier.getCheckCurrentUserManageUsers(moduleCode, userIds);
        
        try {
            //MySQL之IN的优化->https://www.jianshu.com/p/2eea7dd1eb11
            Paginator<ESCustomer> page = esCustomerService.searchByUser(userIds, prole, keyword,level,source, pageNum, pageSize);
            Paginator customerPage = null;
            if(page != null && CollUtil.isNotEmpty(page.getList())){
                List<ESCustomer> list = page.getList();
                List<Long> customerIds = new ArrayList<Long>();
                Set<Long> userIds1 = new HashSet<Long>(); 
                for(ESCustomer esCustomer : list){
                    customerIds.add(esCustomer.getId());
                    userIds1.add(esCustomer.getCreateUserId());
                    userIds1.add(esCustomer.getOwnerUserId());
                }
                
                List<Customer> customers = customerService.findByIds(customerIds);
                List<User> users = userService.findByIds(new ArrayList<>(userIds1));
                if(CollUtil.isNotEmpty(customers)){
                    customerPage = new Paginator<>(page.getTotal(), page.getCurrentPage(), page.getRows());
                    Map<Long, Customer> customerMap = customers.stream().collect(Collectors.toMap(Customer::getId,Function.identity(),(key1, key2) -> key1));
                    
                    Map<Long, String> userMap = null;
                    if(CollUtil.isNotEmpty(users)){
                        userMap = users.stream().collect(Collectors.toMap(User::getId,User::getRealname,(key1, key2) -> key1));
                    }
                    
                    List<CustomerVo> pageList = new ArrayList<>();
                    for(Long customerId : customerIds){
                        Customer customer = customerMap.get(customerId);
                        if(customer != null){
                            String createUser = null;
                            String ownerUser = null;
                            if(userMap != null){
                                createUser = userMap.get(customer.getCreateUserId());
                                ownerUser = userMap.get(customer.getOwnerUserId());
                            }
                            CustomerVo customerVo = new CustomerVo(customer, null, createUser, ownerUser);
                            pageList.add(customerVo);
                        }
                    }
                    customerPage.setList(pageList);
                }
                
            }else{
                customerPage = new Paginator<>(0, pageNum, pageSize); 
            }
            return ResponseResult.success(customerPage);
        } catch (Exception e) {
            throw new UcodeServiceException(ResultCodeEnum.SERVER_ERROR);
        }
    }
    
    
    @PreAuthorize("hasAuthority('crm:customerPool:list') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation("公海客户列表")
    @GetMapping(value = "/poolList")
    public ResponseResult<Object> poolList(
            @ApiParam(value ="客户名称/联系人手机号")  @RequestParam(value = "keywords",required = false) String keyword,
            @ApiParam(value ="客户等级")  @RequestParam(value = "level",required = false) Integer level,
            @ApiParam(value ="客户来源")  @RequestParam(value = "source",required = false) Integer source,
            @ApiParam(value="页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @ApiParam(value="每页记录数",example="20") @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize){
        
        try {
            //MySQL之IN的优化->https://www.jianshu.com/p/2eea7dd1eb11
            Paginator<ESCustomer> page = esCustomerService.searchByPool(keyword,level,source, pageNum, pageSize);
            Paginator customerPage = null;
            if(page != null && CollUtil.isNotEmpty(page.getList())){
                List<ESCustomer> list = page.getList();
                List<Long> customerIds = new ArrayList<Long>();
                Set<Long> userIds1 = new HashSet<Long>(); 
                for(ESCustomer esCustomer : list){
                    customerIds.add(esCustomer.getId());
                    userIds1.add(esCustomer.getCreateUserId());
                }
                
                List<Customer> customers = customerService.findByIds(customerIds);
                List<User> users = userService.findByIds(new ArrayList<>(userIds1));
                if(CollUtil.isNotEmpty(customers)){
                    customerPage = new Paginator<>(page.getTotal(), page.getCurrentPage(), page.getRows());
                    Map<Long, Customer> customerMap = customers.stream().collect(Collectors.toMap(Customer::getId,Function.identity(),(key1, key2) -> key1));
                    
                    Map<Long, String> userMap = null;
                    if(CollUtil.isNotEmpty(users)){
                        userMap = users.stream().collect(Collectors.toMap(User::getId,User::getRealname,(key1, key2) -> key1));
                    }
                    
                    List<CustomerVo> pageList = new ArrayList<>();
                    for(Long customerId : customerIds){
                        Customer customer = customerMap.get(customerId);
                        if(customer != null){
                            String createUser = null;
                            String ownerUser = null;
                            if(userMap != null){
                                createUser = userMap.get(customer.getCreateUserId());
                            }
                            CustomerVo customerVo = new CustomerVo(customer, null, createUser, ownerUser);
                            pageList.add(customerVo);
                        }
                    }
                    customerPage.setList(pageList);
                }
                
            }else{
                customerPage = new Paginator<>(0, pageNum, pageSize); 
            }
            return ResponseResult.success(customerPage);
        } catch (Exception e) {
            throw new UcodeServiceException(ResultCodeEnum.SERVER_ERROR);
        }
    }
    
    @PreAuthorize("hasAuthority('crm:customer:detail') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="根据主键查询")
    @ApiImplicitParam(name = "id", value = "主键ID", required = true, dataType = "String",paramType = "path")
    @GetMapping("/getById/{id}")
    public ResponseResult<Object> getById(@PathVariable(name="id",required=true) Long id){
        
        Customer customer = customerService.findById(id);
        if(customer == null || customer.getDeltag() == 1){
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        }

        Long ownerUserId = customer.getOwnerUserId();
        //数据读写权限标识,该标识告诉前端不要展示一些操作按钮
        Integer power = null;
        String createUser = null;
        String ownerUser = null;
        if(ownerUserId != null && !ownerUserId.equals(0L)){
            List<Long> ownerUserIds = Arrays.asList(ownerUserId);
            power = dataPermissionVerifier.getCurrentUserPowerByBusinessData(moduleCode, ModuleType.customer, customer.getId(), ownerUserIds);
            List<User> users = userService.findByIds(Arrays.asList(ownerUserId,customer.getCreateUserId()));
            if(CollUtil.isNotEmpty(users)){
                Map<Long, String> userMap = users.stream().collect(Collectors.toMap(User::getId,User::getRealname,(key1, key2) -> key1));
                createUser = userMap.get(customer.getCreateUserId());
                ownerUser = userMap.get(customer.getOwnerUserId());
            }
        }else{
            power = TeamUserPower.read.code;//公海客户，只能读取
            User user = userService.findById(customer.getCreateUserId());
            if(user != null){
                createUser = user.getRealname();
            }
        }
        CustomerVo customerVo = new CustomerVo(customer, power, createUser, ownerUser);
        return ResponseResult.success(customerVo);
    }
    
    @PreAuthorize("hasAuthority('crm:customer:detail') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation("客户联系人列表")
    @ApiImplicitParam(name = "customerId", value = "客户ID", required = true, dataType = "String",paramType = "path")
    @GetMapping(value = "/contactsList/{customerId}")
    public ResponseResult<Object> contactsList(@PathVariable(name="customerId",required=true) Long customerId){
        
        Customer customer = customerService.findById(customerId);
        if(customer == null || customer.getDeltag() == 1){
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        }

        Long ownerUserId = customer.getOwnerUserId();
        if(ownerUserId != null && !ownerUserId.equals(0L)){
            List<Long> ownerUserIds = Arrays.asList(ownerUserId);
            dataPermissionVerifier.getCurrentUserPowerByBusinessData(moduleCode, ModuleType.customer, customer.getId(), ownerUserIds);
        }
        
        List<Contacts> list = contactsService.findListByCustomerId(customerId);
        return ResponseResult.success(list);
    }
    
    @PreAuthorize("hasAuthority('crm:customer:detail') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation("客户商机列表")
    @ApiImplicitParam(name = "customerId", value = "客户ID", required = true, dataType = "String",paramType = "path")
    @GetMapping(value = "/businessList/{customerId}")
    public ResponseResult<Object> businessList(@PathVariable(name="customerId",required=true) Long customerId,
            @ApiParam(value="页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @ApiParam(value="每页记录数",example="20") @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize){
        
        Customer customer = customerService.findById(customerId);
        if(customer == null || customer.getDeltag() == 1){
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        }

        Long ownerUserId = customer.getOwnerUserId();
        if(ownerUserId != null && !ownerUserId.equals(0L)){
            List<Long> ownerUserIds = Arrays.asList(ownerUserId);
            dataPermissionVerifier.getCurrentUserPowerByBusinessData(moduleCode, ModuleType.customer, customer.getId(), ownerUserIds);
        }
        
        Paginator<BusinessVo> paginator = businessService.queryPageByCustomer(customerId, pageNum, pageSize);
        return ResponseResult.success(paginator);
    }
    
    @PreAuthorize("hasAuthority('crm:customer:edit') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="创建")
    @PostMapping("/create")
    public ResponseResult<Object> create(@Validated({AddGroup.class}) @RequestBody CustomerForm form) {
        
        Long currentUserId = currentLoginUserService.getCurrentUserId();
        Customer customer = new Customer(form.getName(), form.getLevel(), form.getSource(), form.getIndustry(), form.getNextTime(), form.getWebsite(), form.getRemark(), form.getProvinceId(),form.getCityId(), form.getAreaId(), form.getAddress(), form.getMobile(), form.getTelephone(), form.getSex(), form.getCname(), form.getBirthday(),form.getContactsId());
        customer.setLastTime(new Date());
        customer.setCreateUserId(currentUserId);
        customer.setOwnerUserId(currentUserId);
        
        customer = customerService.insert(customer);
        return ResponseResult.success(customer);
    }
    
    @PreAuthorize("hasAuthority('crm:customer:edit') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="更新")
    @ApiImplicitParam(name = "id", value = "客户ID", required = true, dataType = "String",paramType = "path")
    @PostMapping("/update/{id}")
    public ResponseResult<Object> update(@PathVariable(name="id",required=true) Long id,
            @Validated({UpdateGroup.class}) @RequestBody CustomerForm form) {
        
        Customer dbcustomer = customerService.findById(id);
        if(dbcustomer == null || dbcustomer.getDeltag() == 1)
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        
        Long ownerUserId = dbcustomer.getOwnerUserId();
        
        //公海客户不可编辑
        if(ownerUserId == null || ownerUserId.equals(0L)){
            throw new UcodeServiceException(ResultCodeEnum.ILLEGAL_OPERATION.code,CrmResultDefineMsg.customer_pool_edit_error,dbcustomer.getName());
        }
        
        //校验数据编辑权限
        dataPermissionVerifier.checkCurrentUserWritePowerByBusinessData(moduleCode, ModuleType.customer, dbcustomer.getId(),  Arrays.asList(ownerUserId), CrmResultDefineMsg.customer_edit_permission_error, dbcustomer.getName());
        
        Customer customer = new Customer(form.getName(), form.getLevel(), form.getSource(), form.getIndustry(), form.getNextTime(), form.getWebsite(), form.getRemark(), form.getProvinceId(),form.getCityId(), form.getAreaId(), form.getAddress(), form.getMobile(), form.getTelephone(),  form.getSex(), form.getCname(), form.getBirthday(), form.getContactsId());
        customer.setId(id);
        int i = customerService.update(customer);
        
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }
    
    @PreAuthorize("hasAuthority('crm:customer:delete') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="非公海删除客户")
    @PostMapping("/delete")
    public ResponseResult<Object> delete(
            @ApiParam(value="客户Ids",required=true) @Size(min = 1,max=20,message="一次能操作1-20条记录")@RequestParam(value = "ids", required=true) List<Long> ids) {
        
        Long currentUserId = currentLoginUserService.getCurrentUserId();
        
        List<Customer> customers = customerService.findByIds(ids);
        if(CollUtil.isNotEmpty(customers)){
             for(Customer customer : customers){
                 if(customer.getDeltag() == 1)
                     continue;
                 
                Long ownerUserId = customer.getOwnerUserId();
                if(ownerUserId == null || ownerUserId.equals(0L)){
                    throw new UcodeServiceException(ResultCodeEnum.FAILED.code,CrmResultDefineMsg.customer_existed_pool_delete_error,customer.getName());
                }
                //校验权限
                dataPermissionVerifier.checkCurrentUserOwnerPowerByBusinessData(moduleCode,ModuleType.customer, Arrays.asList(ownerUserId), CrmResultDefineMsg.customer_delete_permission_error, customer.getName());
                customerService.deleteByLogic(customer.getId());
            }
        }
        return ResponseResult.success();
    }
    
    @PreAuthorize("hasAuthority('crm:customerPool:delete') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="公海删除客户")
    @PostMapping("/deletePool")
    public ResponseResult<Object> deletePool(
            @ApiParam(value="客户Ids",required=true) @Size(min = 1,max=20,message="一次能操作1-20条记录")@RequestParam(value = "ids", required=true) List<Long> ids) {
        
        Long currentUserId = currentLoginUserService.getCurrentUserId();
        
        List<Customer> customers = customerService.findByIds(ids);
        if(CollUtil.isNotEmpty(customers)){
             for(Customer customer : customers){
                 if(customer.getDeltag() == 1)
                     continue;
                Long ownerUserId = customer.getOwnerUserId();
                
                if(!ownerUserId.equals(0L) || customerService.deleteByLogic(customer.getId()) == 0){
                    throw new UcodeServiceException(ResultCodeEnum.FAILED.code,CrmResultDefineMsg.customer_pool_delete_error,customer.getName());
                }
            }
        }
        return ResponseResult.success();
    }
    
    @PreAuthorize("hasAuthority('crm:customer:transfer') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="转移")
    @PostMapping("/transfer")
    public ResponseResult<Object> transfer(
            @ApiParam(value="客户Ids",required=true) @Size(min = 1,max=20,message="一次能操作1-20条记录")@RequestParam(value = "ids", required=true) List<Long> ids,
            @ApiParam(value="新负责人",required=true) @RequestParam(value = "ownerId", required=true) Long ownerId,
            @ApiParam(value="将原负责人:0->移除;1->转为团队成员",required=true) @RequestParam(value = "optType", required=true) Integer optType,
            @ApiParam(value="原负责人转为团队成员后的权限:1->只读2->读写(optType为1时必传)",required=false) @RequestParam(value = "power", required=false)Integer power,
            @ApiParam(value="同步转移(0->联系人1-商机2->合同)",required=false) @RequestParam(value = "changeModules", required=false)List<Integer> changeModules) {
        
        Long currentUserId = currentLoginUserService.getCurrentUserId();
        
        List<Customer> customers = customerService.findByIds(ids);
        if(CollUtil.isNotEmpty(customers)){
            for(Customer customer : customers){
                
                Long ownerUserId = customer.getOwnerUserId();
                //公海客户不可转移
                if(ownerUserId == null || ownerUserId.equals(0L)){
                    throw new UcodeServiceException(ResultCodeEnum.FAILED.code,CrmResultDefineMsg.customer_pool_transfer_error,customer.getName());
                }
                
                //校验权限
                dataPermissionVerifier.checkCurrentUserOwnerPowerByBusinessData(moduleCode,ModuleType.customer, Arrays.asList(ownerUserId), CrmResultDefineMsg.customer_transfer_permission_error, customer.getName());
                int i = customerService.transfer(customer.getId(), ownerId, currentUserId);
                //将原负责人变为团队成员，如果重新加入团队异常,直接忽略
                if(i > 0 && optType.equals(1)){
                    crmTeamUserService.batchInsert(customer.getId(), ModuleType.customer.code, Arrays.asList(ownerUserId), power.intValue() == 2 ?TeamUserPower.readWrite.code:TeamUserPower.read.code);
                 }
                if(CollUtil.isNotEmpty(changeModules)){
                    for(Integer module : changeModules){
                        if(module.equals(1)){
                          //同步转移商机
                            
                        }else if(module.equals(2)){
                          //同步转移合同
                            
                        }
                    }
                }
            }
        }
        
        return ResponseResult.success();
    }
    
    @PreAuthorize("hasAuthority('crm:customer:putInPool') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="放入公海")
    @PostMapping("/putInPool")
    public ResponseResult<Object> putInPool(@ApiParam(value="客户Ids",required=true) @Size(min = 1,max=20,message="一次能操作1-20条记录")@RequestParam(value = "ids", required=true) List<Long> ids) {
        Long currentUserId = currentLoginUserService.getCurrentUserId();
        List<Customer> customers = customerService.findByIds(ids);
        if(CollUtil.isNotEmpty(customers)){
            for(Customer customer : customers){
                Long ownerUserId = customer.getOwnerUserId();
                if(ownerUserId == null || ownerUserId.equals(0L))
                    continue;
                
               //校验权限
               dataPermissionVerifier.checkCurrentUserOwnerPowerByBusinessData(moduleCode, ModuleType.customer, Arrays.asList(ownerUserId), CrmResultDefineMsg.customer_putInPool_permission_error, customer.getName());
               customerService.putInPool(customer.getId(), currentUserId);
            }
        }
        return ResponseResult.success();
    }
    
    @PreAuthorize("hasAuthority('crm:customerPool:distribute') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="公海分配客户")
    @PostMapping("/distribute")
    public ResponseResult<Object> distribute(@ApiParam(value="客户Ids",required=true) @Size(min = 1,max=20,message="一次能操作1-20条记录")@RequestParam(value = "ids", required=true) List<Long> ids,
            @ApiParam(value="负责人",required=true) @RequestParam(value = "ownerUserId", required=true) Long ownerUserId) {
        Long currentUserId = currentLoginUserService.getCurrentUserId();
        
        List<Customer> customers = customerService.findByIds(ids);
        if(CollUtil.isNotEmpty(customers)){
            for(Customer customer : customers){
                if(customer.getOwnerUserId() != null && !customer.getOwnerUserId().equals(0L)){
                    throw new UcodeServiceException(ResultCodeEnum.FAILED.code,CrmResultDefineMsg.customer_pool_receive_error,customer.getName());
                }
                customerService.receive(customer.getId(), ownerUserId, currentUserId);
            }
        }
        return ResponseResult.success();
    }
    
    
    @PreAuthorize("hasAuthority('crm:customerPool:receive') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="公海领取客户")
    @PostMapping("/receive")
    public ResponseResult<Object> receive(@ApiParam(value="客户Ids",required=true) @Size(min = 1,max=20,message="一次能操作1-20条记录")@RequestParam(value = "ids", required=true) List<Long> ids) {
        Long currentUserId = currentLoginUserService.getCurrentUserId();
        for(Long id : ids){
            customerService.receive(id, currentUserId, currentUserId);
        }
        return ResponseResult.success();
    }
    
    @PreAuthorize("hasAuthority('crm:customer:lock') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="客户锁定")
    @PostMapping("/lock")
    public ResponseResult<Object> lock(@ApiParam(value="客户Ids",required=true) @Size(min = 1,max=20,message="一次能操作1-20条记录")@RequestParam(value = "ids", required=true) List<Long> ids,
            @ApiParam(value="状态:0->解锁1->锁定",required=false) @RequestParam(value = "status", required=false)Integer status) {
        
       Long currentUserId = currentLoginUserService.getCurrentUserId();
        
        List<Customer> customers = customerService.findByIds(ids);
        if(CollUtil.isNotEmpty(customers)){
            for(Customer customer : customers){
                Long ownerUserId = customer.getOwnerUserId();
                //公海客户不可锁定
                if(ownerUserId == null || ownerUserId.equals(0L)){
                    throw new UcodeServiceException(ResultCodeEnum.FAILED.code,CrmResultDefineMsg.customer_pool_lock_error,customer.getName());
                }
                
                //校验权限
                dataPermissionVerifier.checkCurrentUserOwnerPowerByBusinessData(moduleCode,ModuleType.customer, Arrays.asList(ownerUserId), CrmResultDefineMsg.customer_transfer_permission_error, customer.getName());
               
                customerService.updateLock(customer.getId(), status);
            }
        }
        
        return ResponseResult.success();
    }
    
    @ApiOperation(value="查询客户跟进团队成员")
    @ApiImplicitParam(name = "customerId", value = "客户ID", required = true, dataType = "String",paramType = "path")
    @GetMapping("/teamUsers/{targetId}")
    public ResponseResult<Object> getTeamUsers(@PathVariable(name="targetId",required=true) Long targetId
//            @ApiParam(value="页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
//            @ApiParam(value="每页记录数",example="20") @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize
            ){
        
        List<CrmTeamUser> followupTeamUsers = crmTeamUserService.findList(targetId, ModuleType.customer.code);
        List<FollowupTeamUserVo> followupTeamUserVos = new ArrayList<>();
        if(CollUtil.isNotEmpty(followupTeamUsers)){
            List<Long> userIds =followupTeamUsers.stream().map(m -> m.getUserId()).distinct().collect(Collectors.toList());
            List<User> users = userService.findByIds(userIds);
            Map<Long, User> userMap = null;
            if(CollUtil.isNotEmpty(users)){
                userMap = users.stream().collect(Collectors.toMap(User::getId,Function.identity(),(key1, key2) -> key1));
            }
            
            for(CrmTeamUser followupTeamUser : followupTeamUsers){
                User user = userMap != null ? userMap.get(followupTeamUser.getUserId()) : null;
                followupTeamUserVos.add(new FollowupTeamUserVo(followupTeamUser, user));
            }
            
        }
        
        return ResponseResult.success(followupTeamUserVos);
    }
    
    @PreAuthorize("hasAuthority('crm:customer:teamEdit') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="添加客户跟进团队成员")
    @PostMapping("/teamUser/add")
    public ResponseResult<Object> addTeamUser(
            @ApiParam(value="客户Id",required=true)@RequestParam(value = "targetId", required=true) Long targetId,
            @ApiParam(value="成员Ids",required=true) @Size(min = 1,max=20,message="一次添加1-20人")@RequestParam(value = "userIds", required=true) List<Long> userIds,
            @ApiParam(value = "权限类型:1、负责人权限2、读写权限3、只读权限",required=true,example="2") @RequestParam(value = "power", required=true)Integer power) {
        
        Customer customer = customerService.findById(targetId);
        if(customer == null || customer.getDeltag() == 1)
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        
        //移除负责人,防止客户端误传负责人进来被覆盖
        userIds.remove(customer.getOwnerUserId());
        
        Long ownerUserId = customer.getOwnerUserId();
        
        //公海客户不可编添加跟进团队
        if(ownerUserId == null || ownerUserId.equals(0L)){
            throw new UcodeServiceException(ResultCodeEnum.ILLEGAL_OPERATION.code,CrmResultDefineMsg.customer_pool_addTeamUser_error,customer.getName());
        }
        
        //校验权限
        dataPermissionVerifier.checkCurrentUserWritePowerByBusinessData(moduleCode, ModuleType.customer, targetId, Arrays.asList(ownerUserId), CrmResultDefineMsg.teamUser_add_permission_error);
        
        //不能添加为负责人权限
        if(TeamUserPower.readWrite.code != power){
            power = TeamUserPower.read.code;
        }
        
        crmTeamUserService.batchInsert(customer.getId(), ModuleType.customer.code, userIds, power);     
        
        return ResponseResult.success();
    }
    
    @PreAuthorize("hasAuthority('crm:customer:teamEdit') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="编辑客户跟进团队成员")
    @PostMapping("/teamUser/update")
    public ResponseResult<Object> updateTeamUser(
            @ApiParam(value="团队成员关系Id",required=true)@RequestParam(name="id",required=true) Long id,
            @ApiParam(value = "权限类型:1、负责人权限(读写)2、读写权限3、只读权限",required=true,example="2") @RequestParam(value = "power", required=true)Integer power) {
        
        CrmTeamUser crmTeamUser = crmTeamUserService.findById(id);
        if(crmTeamUser == null)
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        
        if(ModuleType.customer.code != crmTeamUser.getTargetType())
            throw new UcodeServiceException(ResultCodeEnum.ILLEGAL_OPERATION);
        
        if(TeamUserPower.owner.code == crmTeamUser.getPower())
            throw new UcodeServiceException(ResultCodeEnum.ILLEGAL_OPERATION.code,CrmResultDefineMsg.teamUser_owner_edit_error);
        
        Customer customer = customerService.findById(crmTeamUser.getTargetId());
        if(customer == null || customer.getDeltag() == 1)
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        
        Long ownerUserId = customer.getOwnerUserId();
        //校验权限
        dataPermissionVerifier.checkCurrentUserWritePowerByBusinessData(moduleCode, ModuleType.customer, customer.getId(), Arrays.asList(ownerUserId), CrmResultDefineMsg.teamUser_edit_permission_error);
        
        //不能编辑为负责人权限
        if(TeamUserPower.readWrite.code != power){
            power = TeamUserPower.read.code;
        }
        int i = crmTeamUserService.updatePower(id, power);
        
        return i > 0 ? ResponseResult.success(): ResponseResult.failed();
    }
    
    @PreAuthorize("hasAuthority('crm:customer:teamEdit') or hasRole('CRMADMIN') or hasRole('ADMIN')")
    @ApiOperation(value="移除客户跟进团队成员")
    @PostMapping("/crmTeamUser/remove")
    public ResponseResult<Object> removeTeamUser(
            @ApiParam(value="团队成员关系Ids",required=true) @Size(min = 1,max=20,message="一次能操作1-20条记录")@RequestParam(value = "ids", required=true) List<Long> ids) {
        Long currentUserId = currentLoginUserService.getCurrentUserId();
        List<CrmTeamUser> crmTeamUsers = crmTeamUserService.findByIds(ids);
        if(CollUtil.isNotEmpty(crmTeamUsers)){
            Long customerId = crmTeamUsers.get(0).getId();
            Customer customer = customerService.findById(customerId);
            if(customer == null || customer.getDeltag() == 1)
                throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
            
            Long ownerUserId = customer.getOwnerUserId();
            //校验权限
            dataPermissionVerifier.checkCurrentUserWritePowerByBusinessData(moduleCode, ModuleType.customer, customer.getId(), Arrays.asList(ownerUserId), CrmResultDefineMsg.teamUser_delete_permission_error);
            
            for (CrmTeamUser crmTeamUser : crmTeamUsers) {
                if(!customer.getId().equals(crmTeamUser.getTargetId())){
                    throw new UcodeServiceException(ResultCodeEnum.ILLEGAL_OPERATION);
                }
                
                if(TeamUserPower.owner.code == crmTeamUser.getPower())
                    throw new UcodeServiceException(ResultCodeEnum.ILLEGAL_OPERATION.code,CrmResultDefineMsg.teamUser_owner_delete_error);
            
                crmTeamUserService.delete(crmTeamUser.getId(), currentUserId);
            }
            
        }
        return ResponseResult.success();
    }
    
    @ApiOperation(value="退出客户跟进团队")
    @ApiImplicitParam(name = "id", value = "客户ID", required = true, dataType = "String",paramType = "path")
    @PostMapping("/crmTeamUser/quit/{targetId}")
    public ResponseResult<Object> quitFollowTeam(@PathVariable(name="targetId",required=true) Long targetId){
        
        Long currentUserId = currentLoginUserService.getCurrentUserId();
        CrmTeamUser crmTeamUser = crmTeamUserService.find(targetId, ModuleType.customer.code, currentUserId);
        if(crmTeamUser == null){
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD.code,"不是团队成员,无法退出");
        }
        
        if(TeamUserPower.owner.code == crmTeamUser.getPower())
            throw new UcodeServiceException(ResultCodeEnum.ILLEGAL_OPERATION.code,CrmResultDefineMsg.teamUser_owner_quit_error);
        
        crmTeamUserService.delete(crmTeamUser.getId(), currentUserId);
        
        return ResponseResult.success();
    }

}
